from django.shortcuts import render
from rest_framework.generics import CreateAPIView, ListAPIView
from rest_framework.permissions import IsAuthenticated
from orders.models import OrdersModel
from orders.serializers import OrderModelSerializer, OrderListModelSerializer
from rest_framework.views import APIView
from rest_framework.response import Response
from rest_framework.pagination import PageNumberPagination


# 生成订单
class OrderCreateApiView(CreateAPIView):
    permission_classes = [IsAuthenticated, ]
    queryset = OrdersModel.objects.all()
    serializer_class = OrderModelSerializer


# 获取订单状态选项
class OrderPayStatusChoicesApiView(APIView):

    def get(self, request):
        return Response(OrdersModel.ORDER_STATUS_CHOICES)


class OrderListPageNumberPagination(PageNumberPagination):
    page_size = 5
    page_query_param = 'page'
    page_size_query_param = 'size'
    max_page_size = 10


class OrderListApiView(ListAPIView):
    permission_classes = [IsAuthenticated, ]
    pagination_class = OrderListPageNumberPagination
    # queryset =
    serializer_class = OrderListModelSerializer

    def get_queryset(self):
        user = self.request.user
        query_set = OrdersModel.objects.filter(user=user, is_deleted=False, is_show=True)

        order_status = int(self.request.query_params.get('status', -1))
        # 动态获取配置的订单状态列表
        status_list = [i[0] for i in OrdersModel.ORDER_STATUS_CHOICES]
        # 匹配前端传递的状态，是否存在状态列表中
        if order_status in status_list:
            query_set = query_set.filter(order_status=order_status)

        return query_set.order_by('-id')
